﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using BearUtil;
using Loxodon.Framework.XLua.Editors;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Serialization;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Build;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;
using UnityEngine.UI;
using Debug = UnityEngine.Debug;

public class BearToolWindow : OdinEditorWindow
{
    private static BearToolWindow window;

    private static AddressableAssetSettings aa_setting;

    [MenuItem("Game/MapAtlasCtrl Shift+a #A")]
    public static void OpenWindow()
    {
        window = GetWindow<BearToolWindow>("资源管理");
        window.Show();
        window.position = GUIHelper.GetEditorWindowRect().AlignCenter(600, 750);
    }

    /// <summary>
    /// 获取界面
    /// </summary>
    /// <returns></returns>
    public static BearToolWindow GetWindow()
    {
        if (window == null)
            window = GetWindow<BearToolWindow>("资源管理");
        return window;
    }

    // [BoxGroup("构建"), HideLabel, OdinSerialize]
    // private VersionCtrl version;
    //
    [BoxGroup("GroupsManager"), HideLabel, OdinSerialize]
    public AddressablesGroupsManager gsm;

    [BoxGroup("Asset Variant Manager"), HideLabel, OdinSerialize]
    private AssetVariantManager avm;

    [BoxGroup("File Name Check"), HideLabel, OdinSerialize]
    private FileRenameCheckTool fileNameCheck;

    [BoxGroup("Dependencies Check Tool"), HideLabel, OdinSerialize]
    private AAAssetsDependenciesCheckTool depCheck;
    
    [BoxGroup("TextComp Check Tool"), HideLabel, OdinSerialize]
    private TextComponentCheckTool txtCheck;
    
    [BoxGroup("TexturePackage Tool"), HideLabel, OdinSerialize]
    private TPCommandTool tpCmd;

    
    protected override void OnEnable()
    {
        aa_setting = AssetDatabase.LoadAssetAtPath<AddressableAssetSettings>(
            "Assets/AddressableAssetsData/AddressableAssetSettings.asset");
        if (aa_setting == null)
        {
            Debug.LogError("Addressables setting lost.");
            return;
        }

        gsm = AddressablesGroupsManager.Init();
        if (gsm == null)
        {
            Debug.LogError("AddressablesGroupsManager lost.");
            return;
        }

        avm = AssetVariantManager.Init();
        if (avm == null)
        {
            Debug.LogError("AddressablesGroupsManager lost.");
            return;
        }

        fileNameCheck = FileRenameCheckTool.Init();
        if (fileNameCheck == null)
        {
            Debug.LogError("FileRenameCheckTool lost.");
            return;
        }
        
        depCheck = AAAssetsDependenciesCheckTool.Init();
        if (depCheck == null)
        {
            Debug.LogError("FileRenameCheckTool lost.");
            return;
        }

        txtCheck = TextComponentCheckTool.Init();
        if (txtCheck == null)
        {
            Debug.LogError("TextComponentCheckTool lost.");
            return;
        }
        
        tpCmd = TPCommandTool.Init();
        if (tpCmd == null)
        {
            Debug.LogError("TPCommandTool lost.");
            return;
        }
        // -- hide -- 
        // version = VersionCtrl.LoadData();
    }

    // [GUIColor(0.3f, 0.94f, 0.57f), BoxGroup("构建"), Button("自动化构建", ButtonSizes.Gigantic)]
    private static void AutoBuild()
    {
        BuildAsset();

        // set jar store password
        PlayerSettings.keyaliasPass = "BTkj2021!";
        PlayerSettings.keystorePass = "BTkj2021!";

        BuildPipeline.BuildPlayer(
            EditorBuildSettings.scenes,
            $"debug_Android_{DateTime.Now.ToString("yyyy_MM_dd")}.apk",
            BuildTarget.Android,
            BuildOptions.None);

        // open window
        Process.Start(Application.dataPath + "/..");
    }
    
    private static void BuildAsset()
    {
        if (window == null)
            window = GetWindow<BearToolWindow>("资源管理");

        var version = VersionCtrl.LoadData();

        // for luaBytes
        new PrecompileWizard().Precompile();
        // clear addressable content
        AddressablesPlayerBuildResult result = null;
        var floader = Path.Combine(Application.dataPath,
            $"../ServerData/{EditorUserBuildSettings.activeBuildTarget.ToString()}/{VersionCtrl.Version}");
        if (Directory.Exists(floader)) Directory.Delete(floader, true);

        // for addressable build / update catcalog
        version.UpdateNewUnique();
        if (EditorUtility.DisplayDialog("重新构建", "目前版本从头开始构建将丢失所有的版本信息", "确认", "取消"))
        {
            AddressableAssetSettings.BuildPlayerContent(out result);
        }

        // 生成 version.json
        version.GenerateJson();

        // error stop
        if (result.Error.Length > 0)
        {
            Debug.Log("构建中止");
            return;
        }
    }
}